import axios from "axios"

function loginFn({ payload }) {
  console.log(payload)
  return axios.post(`users/login`, payload)
}

const initialState = {
  user: null,
  token: "",
}

const userModel = {
  namespace: "user",
  state: initialState,
  reducers: {
    setState(state = initialState, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
  },
  effects: {
    *login(action, { put, select, call }) {
      console.log(action)
      try {
        const data = yield call(loginFn, action)
        console.log(data)
        localStorage.setItem("token", data.data.user.token)
        localStorage.setItem("user", JSON.stringify(data.data.user))
        yield put({
          type: "setState",
          payload: {
            user: data.data.user,
          },
        })
        return data
      } catch (e) {
        console.log(e)
      }
    },
    *loadStorage(_, { put }) {
      try {
        const user = JSON.parse(localStorage.getItem("user"))
        const token = localStorage.getItem("token")
        yield put({
          type: "setState",
          payload: {
            user,
            token,
          },
        })
      } catch (e) {
        console.log(e)
      }
    },
  },
  subscriptions: {
    setup({ dispatch }) {
      console.log("store初始化...")
      dispatch({ type: "loadStorage" })
    },
  },
}

export default userModel
